/**
 * formatterUtils.ts
 * Utility functions for formatting XML content using the 'xml-formatter' library.
 */
import format from 'xml-formatter';

// Ensure FormattingOptions is exported
export interface FormattingOptions {
    indentation: string;
    collapseContent: boolean;
    lineSeparator: string; // Allow general string, validation happens elsewhere if needed
}

/**
 * Formats an XML string based on the provided options.
 *
 * @param xmlContent The raw XML string to format.
 * @param options The formatting options (indentation, collapseContent, lineSeparator).
 * @returns The formatted XML string, or the original string if formatting fails.
 * @throws Does not throw, but logs errors to the console.
 */
export function formatXmlWithOptions(
    xmlContent: string,
    options: FormattingOptions
): string {
    if (!xmlContent) {
        return '';
    }

    try {
        // Ensure lineSeparator passed to xml-formatter is one of the allowed types
        // Perform a runtime check/cast if necessary, or ensure options conform earlier
        const formatterOptions: any = {
            indentation: options.indentation,
            collapseContent: options.collapseContent,
            lineSeparator: options.lineSeparator, // Cast or validate if needed
        };
        const formatted = format(xmlContent, formatterOptions);
        return formatted;
    } catch (error: any) {
        console.error('XML Formatting Error using xml-formatter:', error);
        // Return the original content if formatting fails
        return xmlContent;
    }
}

/**
 * Provides default formatting options.
 * Useful if settingsStore is unavailable or for initial setup.
 *
 * @returns A FormattingOptions object with default values.
 */
export function getDefaultFormattingOptions(): FormattingOptions {
    return {
        indentation: '  ', // Default: 2 spaces
        collapseContent: true, // Default: collapse empty tags
        lineSeparator: '\n', // Use valid default
    };
}